package log

import (
	"io"
	"os"
	"time"

	"gitee.com/iece/common/conf"
	fr "github.com/lestrrat-go/file-rotatelogs"
	"github.com/sirupsen/logrus"
	"github.com/spf13/viper"
)

func config() (c LoggerConfig, err error) {
	sub := viper.Sub("logger")
	c = LoggerConfig{
		Level:  "info",
		Out:    "console",
		Format: "text",
	}
	err = sub.Unmarshal(&c, conf.DecoderConfigTagYaml)
	if err != nil {
		return c, err
	}
	return c, nil
}

func ConfigLogger() error {
	c, err := config()
	if err != nil {
		return err
	}

	logrus.SetReportCaller(true)
	logrus.AddHook(NewReportCallerHook())

	level, err := logrus.ParseLevel(c.Level)
	if err != nil {
		return err
	}
	logrus.SetLevel(level)

	if len(c.Out) == 0 || c.Out == "console" {
		logrus.SetOutput(os.Stdout)
	} else {
		write, err := frWrite(c.Out)
		if err != nil {
			return err
		}
		logrus.SetOutput(write)
	}
	switch c.Format {
	case "json":
		logrus.SetFormatter(&logrus.JSONFormatter{})
	case "text":
		logrus.SetFormatter(&logrus.TextFormatter{})
	}
	return nil
}

type LoggerConfig struct {
	Level  string `yaml:"level"`
	Out    string `yaml:"out"`
	Format string `yaml:"format"`
}

func frWrite(file string) (io.Writer, error) {
	w, err := fr.New(
		file+".%Y-%m-%d",
		fr.WithLinkName(file),
		fr.WithMaxAge(time.Duration(24*7)*time.Hour),
		fr.WithRotationTime(time.Duration(24)*time.Hour))
	if err != nil {
		return nil, err
	}

	return w, nil
}
